<template>
  <form action="">
    <div
      class="add_material"
      @click.self="addmaterialClick"
      :style="{
        height: nameshow ? '410px' : '335px',
      }"
    >
      <div class="material_classity" v-show="nameshow">
        <div
          class="material_div"
          v-for="(v, i) in materialclassityList"
          :key="i"
        >
          <div class="material_tit" @click="materialtitClick(i)">
            <p>{{ v.tit }}&emsp;</p>
            <img v-if="v.select" :src="img.xaila" alt="" />
            <img v-else :src="img.fanhui" alt="" />
          </div>
          <div
            class="material_tit_list"
            :style="{ display: v.select ? 'block' : 'none' }"
          >
            <ul class="material_ul">
              <li
                v-for="(v1, i1) in v.list"
                :key="i1"
                class="material_list"
                @click="materialListClick(i, i1)"
                :style="{
                  background: v1.select ? '#f4f4f4' : 'transparent',
                }"
              >
                {{ v1.title }}
              </li>
            </ul>
          </div>
        </div>
      </div>
      <div class="material_name">
        <p>{{ name }}名称</p>
        <div class="material_name_input">
          <input
            type="text"
            v-model.trim="nameClassification"
            @focus="materialnameFocus"
          />
        </div>
      </div>
      <div
        class="material_upload"
        :style="{ width: uploadwidth ? uploadwidth : '120px' }"
      >
        <p class="material_upload_tit" v-show="uploadp">上传图片</p>
        <input
          class="material_upload_file"
          type="file"
          @change="handleFileChange"
          autofocus="autofocus"
        />
        <img
          :src="draw.uploadImg"
          alt=""
          v-show="uploadimg"
          :style="{ width: uploadwidth ? uploadwidth : '120px' }"
        />
      </div>
      <div class="material_tools">
        <div
          class="material_span warn"
          :style="{ opacity: materialspan ? '1' : '0' }"
        >
          查看信息是否完善
        </div>
        <div class="material_tool">
          <div class="material_cancel" @click="materialcountermandClick">
            取消
          </div>
          <div class="material_add" @click="materialaddClick">
            添加新{{ name }}
          </div>
        </div>
      </div>
      <canvas
        id="canvas"
        style="width: 0px; height: 0px; overflow: hidden; opacity: 0"
      ></canvas>
    </div>
  </form>
</template>

<script>
import mixin from "@/utils/mixin";
import { postLogoSave, postMaterialSave } from "@/api/template";
import { requestCode } from "@/utils";
import { getBaseList } from "@/api/user";
export default {
  mixins: [mixin],
  //数据是从tempalte页面传过来
  props: ["name"],
  data() {
    return {
      materialspan: false,
      //上传图片
      uploadwidth: null,
      uploadimg: false,
      uploadp: true,
      draw: {
        imgW: null,
        imgH: null,
        uploadImg: "",
      },
      //保存尺寸
      measure: "",
      //表单数据
      onelevelClassification: "",
      twolevelClassification: "",
      threelevelClassification: [],
      threelevel: [],
      nameClassification: "",
      nameshow: true,
      materialclassityList: [
        {
          tit: "选择一级分类 (单选)",
          select: false,
          list: [],
        },
        {
          tit: "选择二级分类 (单选)",
          select: false,
          list: [],
        },
        {
          tit: "选择标签分类 (多选)",
          select: false,
          list: [],
        },
      ],
    };
  },
  watch: {
    materialspan(val) {
      if (val == true) {
        setTimeout(() => {
          this.materialspan = false;
        }, 2000);
      }
    },
  },
  methods: {
    async baseListValue() {
      let info = await getBaseList({ parentId: 0, dataType: 1 });
      if (info.data.data) {
        info.data.data.forEach((v) => {
          v.select = false;
          this.materialclassityList[0].list.push(v);
        });
      }
      let info1 = await getBaseList({
        parentId: info.data.data[0].dataId,
        dataType: 1,
      });
      if (info1.data.data) {
        info1.data.data.forEach((v) => {
          v.select = false;
          this.materialclassityList[1].list.push(v);
        });
      }
      let info2 = await getBaseList({ parentId: 0, dataType: 2 });
      if (info2.data.data) {
        info2.data.data.forEach((v) => {
          v.select = false;
          this.materialclassityList[2].list.push(v);
        });
      }
    },
    materialnameFocus() {
      this.materialclassityList.forEach((v, i) => {
        if (v.select) this.materialtitSet(i);
        v.select = false;
      });
    },
    //可复用的方法
    materialtitSet(i) {
      if (i == 0) {
        this.classificationSet(
          this.onelevelClassification,
          this.materialclassityList,
          0,
          "选择一级分类 (单选)"
        );
      } else if (i == 1) {
        this.classificationSet(
          this.twolevelClassification,
          this.materialclassityList,
          1,
          "选择二级分类 (单选)"
        );
      } else if (i == 2) {
        let str = this.threelevelClassification.toString();
        this.classificationSet(
          str,
          this.materialclassityList,
          2,
          "选择标签分类 (多选)"
        );
      }
    },
    classificationSet(classify, list, num, text) {
      if (classify) this.$set(list[num], "tit", classify);
      else this.$set(list[num], "tit", text);
    },
    //点击空白
    addmaterialClick() {
      if (this.materialclassityList) this.materialnameFocus();
    },
    //点击tit
    materialtitClick(i) {
      if (this.materialclassityList) {
        if (this.materialclassityList[i].select) {
          this.$set(this.materialclassityList[i], "select", false);
          this.materialtitSet(i);
        } else this.$set(this.materialclassityList[i], "select", true);
      }
    },
    //列表选中
    materialListClick(i, i1) {
      if (i == 0 || i == 1) {
        this.materialclassityList[i].list.forEach((v) => {
          v.select = false;
        });
        this.materialclassityList[i].list[i1].select = true;
        if (i == 0) {
          this.onelevelClassification =
            this.materialclassityList[i].list[i1].dataId;
          let { dataId } = this.materialclassityList[i].list[i1];
          this.baseListVal(dataId);
          this.twolevelClassification = "";
          this.materialclassityList[1].tit = "选择二级分类 (单选)";
        } else
          this.twolevelClassification =
            this.materialclassityList[i].list[i1].dataId;
        this.materialclassityList[i].tit =
          this.materialclassityList[i].list[i1].title;
        this.materialclassityList[i].select = false;
        //第三级
      } else if (i == 2) {
        this.materialclassityList[i].list.forEach((v, i2) => {
          //遍历列表 进行选择
          if (i2 == i1) {
            //如果值相等  进行反选
            if (v.select) {
              //如果当前已经被选中
              this.threelevelClassification.forEach((v1) => {
                if (v1 == v.title) {
                  let index = this.threelevelClassification.indexOf(v.title);
                  this.threelevelClassification.splice(index, 1);
                  this.threelevel.splice(index, 1);
                }
              });
            } else {
              this.threelevelClassification.push(v.title);
              this.threelevel.push(v.dataId);
            }
            v.select = !v.select;
          }
          this.materialclassityList[i].tit =
            this.threelevelClassification.toString();
        });
      }
    },
    //添加插图
    handleFileChange(e) {
      let that = this;
      e.stopPropagation();
      const file = e.target.files[0];
      if (!file.type.includes("image")) {
        // toast("只能放图片", "error");
        alert("只能放图片");
        return;
      }
      let res;
      if (this.name == "模板") res = that.$datatools.compressedBack(file);
      else res = that.$datatools.compressedImage(file);
      res.then((result) => {
        that.uploadimg = true;
        that.uploadp = false;
        const reader = new FileReader();
        reader.onload = (res) => {
          that.draw.uploadImg = res.target.result;
          const img1 = new Image();
          img1.onload = () => {
            let n = (120 / img1.height) * img1.width;
            that.uploadwidth = n + "px";
            that.draw.imgW = img1.width;
            that.draw.imgH = img1.height;
          };
          img1.src = that.draw.uploadImg;
        };
        reader.readAsDataURL(result);
      });
    },
    //取消
    materialcountermandClick() {
      //关闭窗口
      this.$emit("childByValue", false);
    },
    //添加
    async materialaddClick() {
      //如果名字和图片都有值的话通过，并且关闭这个弹窗。否则不进行任何操作
      let falg = null; //1 过 //0 不过
      if (this.name == "logo" || this.name == "自定义logo库") falg = 1;
      else if (this.name == "模板" || this.name == "素材") {
        if (this.onelevelClassification && this.twolevelClassification)
          falg = 1;
      }
      if (this.nameClassification && this.draw.imgW && falg == 1) {
        //添加logo
        let logoTag = this.$datatools.TextToPinyin(this.nameClassification);
        //这里对base64串进行操作，去掉url头，并转换为byte
        let array = this.$datatools.baseToType(this.draw.uploadImg);
        let userId = window.localStorage.getItem("eplatformid");
        let token = window.localStorage.getItem("eplatformtoken");
        this.$emit("childByValue", false);
        if (userId && token) {
          if (this.name == "模板") {
            if (!this.nameClassification) {
              this.$message.error("模板名称必填");
              return;
            }
            if (!this.onelevelClassification) {
              this.onelevelClassification = 0;
            }
            if (!this.twolevelClassification) {
              this.twolevelClassification = 0;
            }
            this.$store.commit("templateStage/clearRules");
            this.$emit("childByImg", this.draw);
            this.$store.commit(
              "templateStage/KONVANAME",
              this.nameClassification
            );
            this.$store.commit("templateStage/KONVATEXT", {
              onelevel: this.onelevelClassification,
              twolevel: this.twolevelClassification,
              threelevel: this.threelevel.toString(),
            });
          } else if (this.name == "素材") {
            //添加素材
            let fd = new FormData();
            let blob = new Blob([new Uint8Array(array)], { type: "image/png" });
            fd.append("materialId", "");
            fd.append("dataType", 1);
            fd.append("materialName", this.nameClassification);
            fd.append("materialTag", logoTag);
            fd.append("firstType", this.onelevelClassification);
            fd.append("secondType", this.twolevelClassification);
            fd.append("tagIds", this.threelevel.toString());
            fd.append("file", blob, `${this.nameClassification}.png`);
            fd.append("userId", userId);
            fd.append("token", token);
            let info = await postMaterialSave(fd);
            this.$parent.RequestMaterialData();
            requestCode(info, "保存成功", "网络超时");
          } else if (this.name == "logo") {
            let fd = new FormData();
            let blob = new Blob([new Uint8Array(array)], { type: "image/png" });
            fd.append("logoId", "");
            fd.append("dataType", 0);
            fd.append("logoName", this.nameClassification);
            fd.append("logoTag", logoTag);
            fd.append("file", blob, `${this.nameClassification}.png`);
            fd.append("userId", userId);
            fd.append("token", token);
            let info = await postLogoSave(fd);
            this.$parent.RequestLogoData();
            requestCode(info, "保存成功", "网络超时");
          } else if (this.name == "自定义logo库") {
            let fd = new FormData();
            let blob = new Blob([new Uint8Array(array)], { type: "image/png" });
            fd.append("logoId", "");
            fd.append("dataType", 1);
            fd.append("logoName", this.nameClassification);
            fd.append("logoTag", logoTag);
            fd.append("file", blob, `${this.nameClassification}.png`);
            fd.append("userId", userId);
            fd.append("token", token);
            let info = await postLogoSave(fd);
            this.$parent.RequestCusLogoData();
            requestCode(info, "保存成功", "网络超时");
          }
          // else if (this.name == "自定义素材库") {
          //   let fd = new FormData();
          //   let blob = new Blob([new Uint8Array(array)], { type: "image/png" });
          //   fd.append("materialId", "");
          //   fd.append("dataType", 1);
          //   fd.append("materialName", this.nameClassification);
          //   fd.append("materialTag", logoTag);
          //   fd.append("firstType", 0);
          //   fd.append("secondType", 0);
          //   fd.append("tagIds", "");
          //   fd.append("file", blob, `${this.nameClassification}.png`);
          //   fd.append("userId", userId);
          //   fd.append("token", token);
          //   let info = await postMaterialSave(fd);
          //   this.$parent.RequestCusMaterialData();
          //   requestCode(info, "保存成功", "网络超时");
          // }
        }
        //去登录
        else this.$emit("relogin");
      } else this.materialspan = true;
    },
    shuangchuan() {},
    async baseListVal(parentId) {
      let info = await getBaseList({ parentId, dataType: 1 });
      this.materialclassityList[1].list = [];
      if (info.data.data) {
        info.data.data.forEach((v) => {
          v.select = false;
          this.materialclassityList[1].list.push(v);
        });
      }
    },
  },
  created() {
    this.baseListValue();
  },
  mounted() {
    if (
      this.name == "logo" ||
      this.name == "自定义素材库" ||
      this.name == "自定义logo库"
    )
      this.nameshow = false;
    else this.nameshow = true;
  },
};
</script>

<style lang="less" scoped>
@import "../../assets/styles/frame.less";
@keyframes aaa {
  0% {
    opacity: 0;
    transform: translate3d(0, -10%, 0);
  }
  100% {
    opacity: 1;
    transform: none;
  }
}
.add_material {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  z-index: 99999;
  width: 700px;
  background: #fff;
  padding: 30px 24px 25px 24px;
  border-radius: @radius1;
  box-shadow: @shadow;
  color: @color2;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .material_classity {
    width: 100%;
    .divAJ();
    .material_div {
      width: 31%;
      height: 100%;
      position: relative;
      .material_tit {
        width: 100%;
        height: 36px;
        border: 2px solid @color6;
        padding: 0 14px;
        .divAJS();
        img {
          width: 12px;
          height: 6px;
        }
      }
      .material_tit_list {
        animation: aaa 0.3s linear;
        position: absolute;
        top: 36px;
        left: 0;
        width: 100%;
        height: 150px;
        padding: 16px 4px 16px 8px;
        border-radius: @radius2;
        box-shadow: 0px 4px 5px #c1bebe6c;
        z-index: 55;
        background: #fff;
        .material_ul {
          width: 100%;
          height: 100%;
          overflow-y: auto;
          .material_list {
            width: 160px;
            height: 32px;
            padding-left: 4px;
            line-height: 32px;
            cursor: pointer;
          }
        }
      }
    }
  }
  .material_name {
    width: 100%;
    height: 36px;
    .divDA();
    .material_name_input {
      width: 200px;
      height: 40px;
      border: 2px solid @color5;
      padding: 0 10px;
      margin-left: 8px;
      border-radius: @radius3;
      .divDA();
      input {
        width: 100%;
      }
    }
  }
  .material_upload {
    position: relative;
    width: 120px;
    height: 120px;
    border: 2px solid @color5;
    border-radius: 2px;
    .cen();
    .material_upload_tit {
      font-size: 14px;
      color: @color1;
    }
    img {
      width: 120px;
    }
    input {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      opacity: 0;
    }
  }

  .material_tools {
    width: 100%;
    height: 54px;
    font-size: 14px;
    .material_span {
      width: 100%;
      height: 14px;
      text-align: center;
      margin-bottom: 14px;
    }
    .material_tool {
      height: 36px;
      .divDJ();

      .material_cancel {
        cursor: pointer;
        float: left;
        width: 200px;
        height: 100%;
        margin-right: 68px;
        border: 2px solid @color5;
        border-radius: @radius3;
        color: @color1;
        .cen();
      }
      .material_add {
        cursor: pointer;
        float: left;
        width: 200px;
        height: 100%;
        background-color: @color7;
        color: #fff;
        border-radius: @radius3;
        .cen();
      }
    }
  }
}
</style>


 